/**
 * @Author: wzx
 * @Description:
 * @Version: 1.0.0
 * @Date: 2021/6/29 下午8:09
 *@Copyright: MIN-Group；国家重大科技基础设施——未来网络北大实验室；深圳市信息论与未来网络重点实验室
 */

package network

import (
	"minlib/logicface"
	"minlib/security"
	"vpn-management-server/logger"
	"vpn-management-server/lru"
	"vpn-management-server/security/keymanager"
)

type MINNet struct {
	logicface.LogicFace
	KeyChain  *security.KeyChain
	key       *keymanager.KeyManager // 密钥管理
	serverKey *keymanager.KeyManager //just pubkey can be used
	Cache     *lru.Cache
}

func (mnet *MINNet) SetSecKey(key *keymanager.KeyManager) {
	mnet.key = key
}

func (mnet *MINNet) Listens(prefix string) error {
	if err := mnet.InitWithUnixSocket(prefix); err != nil {
		logger.Logger.Error(err)
		return err
	}

	// 如果要进行包签名的话，则需要加入KeyChain
	KeyChain, err := security.CreateKeyChain()
	if err != nil {
		logger.Logger.Error("create keyChain fail", err.Error())
		return err
	}

	// 获取身份，这个身份已经存储在本地数据库中，创建方法见KeyChain.go
	i := KeyChain.IdentityManager.GetIdentityByName("/vms")
	// 将身份对应的加密秘钥作为第二个参数传入
	err = KeyChain.SetCurrentIdentity(i, "Aa123456")
	if err != nil {
		logger.Logger.Error("set identity fail", err.Error())
		return err
	}

	mnet.SetKeyChain(KeyChain)
	mnet.KeyChain = KeyChain
	return nil
}

func (mnet *MINNet) Listen(portOrPrefix string) error {
	if err := mnet.InitWithUnixSocket(portOrPrefix); err != nil {
		logger.Logger.Error(err)
		return err
	}
	return nil
}
